package com.wendy.common.dao.mybatis.handler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @Author: ALEX WANG
 * @Date: 2020/3/24 9:43
 */
@MappedTypes({})
public class ToJsonObjectTypeHandler<T>  extends BaseTypeHandler <T> {
    private Class<T> clazz;

    public ToJsonObjectTypeHandler(Class<T> clazz) {
        this.clazz = clazz;
    }
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException {
        ObjectMapper mapper= new ObjectMapper();
        if (parameter != null) {
            try {
                ps.setObject(i,  mapper.writeValueAsString(parameter));
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }
    }
    @SneakyThrows
    @Override
    public T getNullableResult(ResultSet rs, String columnName) throws SQLException {
        ObjectMapper mapper= new ObjectMapper();
        String  r=rs.getString(columnName);
        if(StringUtils.isBlank(r)){
            return  null;
        }
        T result = mapper.readValue(r, new TypeReference<T>() {
        });
        return result;
    }




    @SneakyThrows
    @Override
    public T getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        ObjectMapper mapper= new ObjectMapper();
        String  r=rs.getString(columnIndex);
        if(StringUtils.isBlank(r)){
            return  null;
        }
        T result = mapper.readValue(r, new TypeReference<T>() {
        });
        return result;
    }

    @SneakyThrows
    @Override
    public T getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        ObjectMapper mapper= new ObjectMapper();
        String  r=cs.getString(columnIndex);
        if(StringUtils.isBlank(r)){
            return  null;
        }
        T result = mapper.readValue(r, new TypeReference<T>() {
        });
        return result;
    }
}
